package com.qudian.pay.redis;

import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import com.qudian.pay.redis.exception.RedisException;
import com.qudian.pay.redis.support.ICommon;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Pool;

public class RedisManager implements ICommon<String> {
	
	protected final Charset charset = Charset.forName("UTF8");
	
	@Resource
	protected ShardedJedisPool jedisPool;
	
	@Resource
	protected ShardedJedisPool jedisPoolRead;
	
	public Pool<ShardedJedis> getPool() {
		return jedisPool;
	}
	
	public Pool<ShardedJedis> getReadPool() {
		if (null == this.jedisPoolRead)
			return jedisPool;
		else
			return this.jedisPoolRead;
	}
	
	@Override
	public void delete(String key) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			jedis.del(key);
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public void deleteAll(Collection<String> keys) {
		for (String key : keys) {
			delete(key);
		}
	}
	
	@Override
	public boolean isExist(String key) {
		ShardedJedis jedis = this.getReadPool().getResource();
		try {
			return jedis.exists(key);
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public Set<String> keys(String pattern) {
		throw new RedisException(-1, "集群模式暂不支持[KEYS]操作");
	}
	
	protected byte[][] toByteArrays(Map<byte[], byte[]> source) {
		byte[][] result = new byte[source.size() * 2][];
		int index = 0;
		for (Map.Entry<byte[], byte[]> entry : source.entrySet()) {
			result[index++] = entry.getKey();
			result[index++] = entry.getValue();
		}
		return result;
	}
}
